package com.tommy.jiami.utils;

import android.content.*;
import android.os.Build;

import com.tommy.jiami.utils.task.*;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.*;

import javax.crypto.*;
import javax.crypto.spec.*;

public class Crypt {
    public static final String DEFAULT_PASSWORD="tommy0607";
    public static byte[] encrypt(byte[] data, String password) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(getRawKey(password.getBytes()), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(data);
        return encrypted;
    }

    public static byte[] decrypt(byte[] src, String password) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(getRawKey(password.getBytes()), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        byte[] decrypted = cipher.doFinal(src);
        return decrypted;
    }

    public static String encryptString(String data, String password) throws Exception {
        byte[] result = encrypt(data.getBytes(), password);
        return toHex(result);
    }

    public static String decryptString(String src, String password) throws Exception {
        byte[] result = decrypt(toByte(src), password);
        return new String(result);
    }

    public static void encryptFile(String fromPath, String toPath, String password, boolean isDelete) throws Exception {
        FileInputStream input = new FileInputStream(fromPath);
        FileOutputStream output = new FileOutputStream(toPath);
        byte[] buf = new byte[input.available()];
        input.read(buf);
        buf = encrypt(buf, password);
        output.write(buf);
        output.close();
        input.close();
        if (isDelete) new File(fromPath).delete();
    }

    public static void decryptFile(String fromPath, String toPath, String password, boolean isDelete) throws Exception {
        FileInputStream input = new FileInputStream(fromPath);
        FileOutputStream output = new FileOutputStream(toPath);
        byte[] buf = new byte[input.available()];
        input.read(buf);
        buf = decrypt(buf, password);
        output.write(buf);
        output.close();
        input.close();
        if (isDelete) new File(fromPath).delete();
    }

    public static void encryptFileWithDialog(Context context, String fromPath, String toPath, String password, boolean isDelete) {
        CryptFileTask task = new CryptFileTask(context, TYPE_ENCRYPT, isDelete);
        task.execute(fromPath, toPath, password);
    }

    public static void decryptFileWithDialog(Context context, String fromPath, String toPath, String password, boolean isDelete) {
        CryptFileTask task = new CryptFileTask(context, TYPE_DECRYPT, isDelete);
        task.execute(fromPath, toPath, password);
    }

    private static String toHex(byte[] buf) {
        final String HEX = "0123456789ABCDEF";
        if (buf == null)
            return "";
        StringBuffer result = new StringBuffer(2 * buf.length);
        for (int i = 0; i < buf.length; i++) {
            result.append(HEX.charAt((buf[i] >> 4) & 0x0f)).append(
                    HEX.charAt(buf[i] & 0x0f));
        }
        return result.toString();
    }

    private static byte[] toByte(String hexString) {
        int len = hexString.length() / 2;
        byte[] result = new byte[len];
        for (int i = 0; i < len; i++)
            result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2),
                    16).byteValue();
        return result;
    }

    private static byte[] getRawKey(byte[] seed) throws Exception {
        SecretKey skey;
        if (Build.VERSION.SDK_INT < 24) {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            SecureRandom sr;
            if (Build.VERSION.SDK_INT >= 24)
                sr = SecureRandom.getInstance("1PRNG");
            else
                sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
            sr.setSeed(seed);
            kgen.init(128, sr); // 192 and 256 bits may not be available
            skey = kgen.generateKey();
        } else {
            skey = new SecretKeySpec(
                    InsecureSHA1PRNGKeyDerivator.deriveInsecureKey(
                            seed, 32),
                    "AES");
        }
        byte[] raw = skey.getEncoded();
        return raw;
    }

    private static SecretKey deriveKeyInsecurely(String password, int
            keySizeInBytes) {
        byte[] passwordBytes = password.getBytes(StandardCharsets.US_ASCII);
        return new SecretKeySpec(
                InsecureSHA1PRNGKeyDerivator.deriveInsecureKey(
                        passwordBytes, keySizeInBytes),
                "AES");
    }

    public final static int TYPE_ENCRYPT = -1;
    public final static int TYPE_DECRYPT = -2;
}
